package com.slipper.ai.flow.support;

import com.slipper.ai.flow.INodeDealer;
import com.slipper.ai.flow.Parser;
import com.slipper.ai.flow.vo.*;
import com.slipper.ai.service.ChatService;
import com.slipper.system.ai.bo.AiModelBO;
import com.slipper.system.ai.service.AiModelService;
import com.slipper.util.BeanUtil;
import com.slipper.util.Tool;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component("aiLlmNodeDealer")
public class LlmNodeDealer implements INodeDealer {
    @Resource
    private AiModelService aiModelService;
    @Resource
    private ChatService chatService;

    @Override
    public String getType() {
        return NodeVO.TYPE_LLM;
    }

    @Override
    public List<LineVO> doDeal(FlowVO flow, NodeVO node, NodeInstVO nodeInst) {
        if (!(node instanceof LlmNodeVO llmNode))  throw new RuntimeException("节点类型不正确！");
        if (Tool.isBlank(llmNode.getUserPrompt())) throw new RuntimeException("用户消息不能为空！");

        AiModelBO aiModel = aiModelService.queryBy(llmNode.getModelId());
        if (Tool.isNotBlank(llmNode.getModelParamJson())) {
            aiModel.setParamJson(BeanUtil.concatMapJson(aiModel.getParamJson(), llmNode.getModelParamJson()));
        }

        String userMessage = Parser.parseSymbol(llmNode.getUserPrompt(), nodeInst.getInput());
        String assistantMessage = chatService.chat(
                flow.getSessionId(),
                llmNode.getHistoryCount(),
                Parser.parseSymbol(llmNode.getSystemPrompt(), nodeInst.getInput()),
                userMessage,
                aiModel);

        Map<String, Object> outputMap = new HashMap<>();
        outputMap.put("结果", assistantMessage);
        nodeInst.setOutput(outputMap);

        return flow.getLines()
                .stream()
                .filter(line -> line.getSource().equals(node.getId()))
                .collect(Collectors.toList());
    }
}
